package bright.phonenumber;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
 * java bright.phonenumber.ConvertApp <srcFileName> [destFileName]
 */
public class ConvertApp 
{
	public static final String DEST_POSTFIX = ".converted.txt";
	
	private Converter converter;
	private String srcFileName;
	private String destFileName;
	
	public static void main( String args[] )
	{
		String srcfn = null;
		String destfn = null;
		if( args.length > 0 )
		{
			srcfn = args[0];
		}
		if( args.length > 1 )
		{
			destfn = args[1];
		}
		
		ConvertApp app = new ConvertApp( srcfn, destfn );
		if( !app.convert() )
		{
			error( "can't convert phone list in file: " + srcfn );
		}
		else
		{
			info( "converted phone list inf file: " + srcfn + " to: " + app.getDestFileName() );
		}
	}
	
	public ConvertApp( String srcFileName )
	{
		this( srcFileName, null );
	}
	
	public ConvertApp( String srcFileName, String destFileName )
	{
		this.srcFileName = srcFileName;
		this.destFileName = destFileName;
	}
	public boolean convert()
	{
		if( srcFileName == null || srcFileName.length() == 0 )
		{
			info( "please specify the source file." );
			return false;
		}
		
		String destFileName = getDestFileName();
		
		File srcFile = new File( srcFileName );
		if( !srcFile.exists() )
		{
			error( "source file doesn't exists: " + srcFile.getAbsolutePath() );
			return false;
		}
		if( !srcFile.isFile() )
		{
			error( "it's not a file: " + srcFile.getAbsolutePath() );
			return false;
		}
		
		File destFile = new File( getDestFileName() );
		try
		{
			FileWriter fw = new FileWriter( destFile );
			BufferedWriter bw = new BufferedWriter( fw );
			
			FileReader fr = new FileReader( srcFile );
			BufferedReader br = new BufferedReader( fr );
			while( true )
			{
				String phoneNumber = br.readLine();
				if( phoneNumber == null )
				{
					//end
					bw.flush();
					bw.close();
					fw.close();
					
					br.close();
					fr.close();
					break;
				}
				bw.append( convertPhoneNumber( phoneNumber ) );
				bw.newLine();
			}
			return true;
		}
		catch( IOException ioe )
		{
			error( ioe.getMessage() );
			return false;
		}
	}
	
	public String convertPhoneNumber( String srcPhoneNumber )
	{
		return getConverter().converPhone( srcPhoneNumber );
	}
	
	public Converter getConverter()
	{
		if( converter == null )
		{
			converter = new Converter();
		}
		return converter;
	}
	
	public String getDestFileName()
	{
		if( destFileName != null && destFileName.length() > 0 )
			return destFileName;
		return srcFileName + DEST_POSTFIX;
	}

	public static void error( String error )
	{
		System.err.println( error );
	}

	public static void info( String info )
	{
		System.out.println( info );
	}
}
